package com.example.wmstore.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wmstore.common.QueryPageParam;
import com.example.wmstore.common.Result;
import com.example.wmstore.entity.Inrecord;
import com.example.wmstore.entity.Outrecord;
import com.example.wmstore.entity.User;
import com.example.wmstore.service.InrecordService;
import com.example.wmstore.service.MenuService;
import com.example.wmstore.service.OutrecordService;
import com.example.wmstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TCW
 * @since 2024-05-29
 */


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private InrecordService inrecordService;
    @Autowired
    private OutrecordService outrecordService;
    @GetMapping("/count")
    public Integer count(){
        return userService.list().size();
    }

    @GetMapping("/allcount")
    public Result allcount(){
        HashMap<Object,Object> res=new HashMap<>();
        Integer userCount=userService.lambdaQuery().eq(User::getRole,2).eq(User::getStatus,1).list().size();
        Integer adminCount=userService.lambdaQuery().ne(User::getRole,2).eq(User::getStatus,1).list().size();
        res.put("userCount",userCount);
        res.put("adminCount",adminCount);
        return Result.suc(res);
    }
    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user){
        List<User> list=userService.lambdaQuery().eq(User::getName,user.getName()).eq(User::getRole,2).list();
        if (list.size()>0){
            return Result.fail("昵称重复，请重新输入！");
        }
        list=userService.lambdaQuery().eq(User::getPhone,user.getPhone()).eq(User::getRole,2).list();
        if (list.size()>0){
            return Result.fail("手机号已经被注册，请换一个！");
        }
        return userService.save(user)?Result.suc(user):Result.fail("创建失败");
    }
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        List<User> list=userService.lambdaQuery().eq(User::getName,user.getName()).
                ne(User::getId,user.getId()).eq(User::getRole,2).list();
        if (list.size()>0){
            return Result.fail("昵称重复，请重新输入！");
        }
        list=userService.lambdaQuery().eq(User::getPhone,user.getPhone()).
                ne(User::getId,user.getId()).eq(User::getRole,2).list();
        if (list.size()>0){
            return Result.fail("手机号已经被注册，请换一个！");
        }
        user.setUpdateTime(LocalDateTime.now());
        return userService.updateById(user)?Result.suc():Result.fail();
    }
    @Transactional
    @GetMapping("/delete")
    public Result delete(@RequestParam Long[] ids){
        for (int i=0;i<ids.length;i++){
            User user=userService.getById(ids[i]);
            if(user.getRole()==2){
                inrecordService.lambdaQuery().eq(Inrecord::getUserid,
                        user.getId()).list().forEach(inrecordService::removeById);
                outrecordService.lambdaQuery().eq(Outrecord::getUserid,
                        user.getId()).list().forEach(outrecordService::removeById);
            }else {
                inrecordService.lambdaQuery().eq(Inrecord::getAdminId,
                        user.getId()).list().forEach(inrecordService::removeById);
                outrecordService.lambdaQuery().eq(Outrecord::getAdminId,
                        user.getId()).list().forEach(outrecordService::removeById);
            }
        }
        return userService.removeById(ids)?Result.suc():Result.fail();
    }

    @PostMapping("/deleteLogical/{id}")
    public Result deleteLogical(@PathVariable("id") Long id)
    {
        User user=userService.getById(id);
        user.setStatus(0);
        return userService.updateById(user)?Result.suc():Result.fail();
    }

    @PostMapping("/control/{id}")
    public Result control(@PathVariable("id") Long id){
        User user=userService.getById(id);
        if(user.getStatus()==1){
            user.setStatus(0);
        }else {
            user.setStatus(1);
        }
        return userService.updateById(user)?Result.suc():Result.fail();
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable Long id){
        User user=userService.getById(id);
        return Result.suc(user);
    }

    @GetMapping("/getAvatar/{name}")
    public Result getAvatar(@PathVariable("name") String name){
        List<User> list=userService.lambdaQuery().eq(User::getName,name).list();
        if (list.size()>0){
            return Result.suc(list.get(0).getAvatar());
        }
        list=userService.lambdaQuery().eq(User::getPhone,name).list();
        if (list.size()>0){
            return Result.suc(list.get(0).getAvatar());
        }
        return Result.fail("用户不存在");
    }

    @PostMapping("/listPage")
    public Result listPage(@RequestBody  QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        String phone = (String)param.get("phone");
        String sex = (String)param.get("sex");
        String status = (String)param.get("status");
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper <User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name)&&!"null".equals(name)) {
            lambdaQueryWrapper.like(User::getName, name);
        }
        if(StringUtils.isNotBlank(phone)&&!"null".equals(phone)) {
            lambdaQueryWrapper.like(User::getPhone, phone);
        }
        if(StringUtils.isNotBlank(sex)&&!"null".equals(sex)) {
            lambdaQueryWrapper.eq(User::getSex, sex);
        }
        if(StringUtils.isNotBlank(status)&&!"null".equals(status)) {
            lambdaQueryWrapper.eq(User::getStatus, status);
        }

        IPage result = userService.PageList(page,lambdaQueryWrapper);

        return Result.suc(result.getTotal(), result.getRecords().toString());
    }

    @PostMapping("/adminPage")
    public Result adminPage(@RequestBody  QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        String phone = (String)param.get("phone");
        String sex = (String)param.get("sex");
        String role = (String)param.get("role");
        String status = (String)param.get("status");
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper <User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name)&&!"null".equals(name)) {
            lambdaQueryWrapper.like(User::getName, name);
        }
        if(StringUtils.isNotBlank(phone)&&!"null".equals(phone)) {
            lambdaQueryWrapper.like(User::getPhone, phone);
        }
        if(StringUtils.isNotBlank(sex)&&!"null".equals(sex)) {
            lambdaQueryWrapper.eq(User::getSex, sex);
        }
        if(StringUtils.isNotBlank(role)&&!"null".equals(role)) {
            lambdaQueryWrapper.eq(User::getRole, role);
        }
        if(StringUtils.isNotBlank(status)&&!"null".equals(status)) {
            lambdaQueryWrapper.eq(User::getStatus, status);
        }

        lambdaQueryWrapper.ne(User::getRole,2);
        IPage result = userService.PageList(page,lambdaQueryWrapper);

        return Result.suc(result.getTotal(), result.getRecords().toString());
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        List list = userService.lambdaQuery().eq(User::getName, user.getName()).eq(User::getPassword,user.getPassword()).list();
        if(list.size()>0){
            User user1= (User) list.get(0);
            if(user1.getStatus()!=1){
                return Result.fail("账号无效");
            }else {
                StpUtil.login(user1.getId());
                List Menu=menuService.lambdaQuery().like(com.example.wmstore.entity.Menu::getMenuright,user1.getRole()).list();
                HashMap res=new HashMap();
                res.put("user",user1);
                res.put("menu",Menu);
                return Result.suc(res);
            }
        }
        return Result.fail("账号不存在");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        List<User> list=userService.lambdaQuery().eq(User::getName,user.getName()).eq(User::getRole,2).list();
        if (list.size()>0){
            return Result.fail("昵称重复，请重新输入！");
        }
        list=userService.lambdaQuery().eq(User::getPhone,user.getPhone()).eq(User::getRole,2).list();
        if (list.size()>0){
            return Result.fail("手机号已经被注册，请换一个！");
        }
        return userService.save(user)?Result.suc(user):Result.fail("创建失败");
    }
}
